package com.autotest.nore.common.utils;

import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.client5.http.impl.routing.DefaultProxyRoutePlanner;
import org.apache.hc.client5.http.routing.HttpRoutePlanner;
import org.apache.hc.core5.http.HttpHost;

public class HttpClientWithProxy {

    private static CloseableHttpClient httpClient;

    /**
     * 初始化带代理的 HttpClient
     *
     * @param proxyHost 代理主机
     * @param proxyPort 代理端口
     */
    public HttpClientWithProxy(String proxyHost, int proxyPort) {
        // 创建连接池管理器
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(200);
        cm.setDefaultMaxPerRoute(50);

        // 配置代理
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);

        // 创建 HttpClient
        httpClient = HttpClients.custom()
                .setConnectionManager(cm)
                .setRoutePlanner(routePlanner)
                .build();
    }

    /**
     * 获取带代理的 HttpClient 实例
     *
     * @return CloseableHttpClient
     */
    public CloseableHttpClient getHttpClient() {
        return httpClient;
    }

}
